package cn.tianyigps.tianyigpsapiv2.Intercepetor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IDEA
 * author:guibin.cui
 * Date:2018/12/22
 * Time:14:44
 * 拦截器
 */
@Component
@Slf4j
public class WebHandlerInterceptor implements HandlerInterceptor {
    private static  final String  GBK = "gbk";
    private static  final String  UTF_8 = "utf-8";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("ip:  " + request.getRemoteAddr() + "   request to： " + request.getRequestURI());
//        String key = request.getParameter("key");
//        if (StringUtils.isEmpty(key)){
//            response.setStatus(400);
//            response.setCharacterEncoding(GBK);
//            PrintWriter writer = response.getWriter();
//            BaseDTO baseDTO = new ResponseDTO();
//            baseDTO.response(ResponseEnum.KEY_FAILURE);
//            ObjectMapper objectMapper = new ObjectMapper();
//            String string = objectMapper.writeValueAsString(baseDTO);
//            writer.append(string);
//            return false;
//        }else{
//            String string = null;
//            try {
//                int i = Integer.parseInt(key,16);
//                string = Integer.toBinaryString(i);
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//                response.setStatus(400);
//                response.setCharacterEncoding(GBK);
//                PrintWriter writer = response.getWriter();
//                BaseDTO baseDTO = new ResponseDTO();
//                baseDTO.response(ResponseEnum.KEY_ERROR);
//                ObjectMapper objectMapper = new ObjectMapper();
//                String s = objectMapper.writeValueAsString(baseDTO);
//                writer.append(s);
//                return false;
//            }
//            request.setAttribute("key",string);
//        }

        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        log.info("ip:  " + request.getRemoteAddr() +"    Method : " + request.getMethod() + "   Complete ： " + request.getRequestURI());
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }


}
